package com.matrix.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.MdcUtil;
import com.matrix.core.tools.WebUtil;
/**
 * 通用web请求拦截器
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2017年11月29日
 */
public class WbeCommonInterceptor implements HandlerInterceptor {

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	/**
	 * 通用拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String ip = request.getHeader("X-Forwarded-For");
        if (ip == null) {
            ip = request.getRemoteAddr();
        }
        String userAgent = request.getHeader("User-Agent");

        //设置本次请求的id
		MdcUtil.setRequestId();
		LogUtil.info("#Begin Request# "+"["+WebUtil.getLocation()+"]");
        LogUtil.info("#请求者IP为:{},User-Agent为:{}#", ip, userAgent);
		return true;

	}
 
	@Override
	public void  afterCompletion(HttpServletRequest request, HttpServletResponse response,  Object arg2, Exception arg3) throws Exception {
		
		LogUtil.info("#Finshed Rquest# "+"["+WebUtil.getLocation()+"]");
		//清除本次请求的id
		MdcUtil.clearRequestId();
	}

}
